package baseFx.common.context.spring;

import baseFx.common.Stream;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContextScope implements Scope {
    private List<Runnable> dispenser = new ArrayList<>();
    private Map<String, Object> beans = new ConcurrentHashMap<>();

    public void destroy() {
        if (dispenser != null) {
            Stream.create(dispenser).reverse().foreach(Runnable::run);
            dispenser.clear();
            dispenser = null;
        }
        if (beans != null) {
            beans.clear();
            beans = null;
        }
    }

    @Override
    public Object get(String s, ObjectFactory<?> objectFactory) {
        if (beans.containsKey(s) == false) {
            beans.put(s, objectFactory.getObject());
        }
        return beans.get(s);
    }

    @Override
    public Object remove(String s) {
        return beans.remove(s);
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {
        dispenser.add(runnable);
    }

    @Override
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
